<html>
<div id="loading">
<img src=images/loading.gif> <font color=#008080 size=3><b> Please wait a second ...</b></font>
</div>
<script>
function hideLoading()
{
  var disp = document.getElementById('loading');
  disp.innerHTML = '';
}

</script>

<body>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';
include 'head.htm';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$_SESSION['tab'] = 0;
$act = getHttpVal('act', 'findkey');
$start = getHttpVal('start', 0);
$id=getHttpVal('id',-1);
//echo 'act='.$act.', id='.getHttpVal('id',-1).', counter='.getHttpVal('counter',-1);

if (strcmp($act,'Update')==0 && $id > 0) {

  writeLog("ListUserToken::Main Update call", true);
  $startdate = getHttpVal('startdate', '');
  $enddate = getHttpVal('enddate', '');
  $active = getHttpVal('status', 1);
  $type = getHttpVal('type', 1);
  $user = getHttpVal('user', '');
  
  $stmt = 'UPDATE userkeymap SET start_date='.mysql_quote($startdate).', end_date='.mysql_quote($enddate).
    ', map_status='.$active.', validity_type='.mysql_quote($type);
  $stmt .= ' WHERE map_id='.$id;
  if ($r = query($stmt)) {
    $_SESSION['alert'] = 'User-'.$user.' mapped token was updated successfully';
  } else {
    $_SESSION['alert'] = 'User update failed! '.$contactAdm;
  }
  
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
  
} elseif (strcmp($act,'Delete')==0 && $id > 0) {

  writeLog("ListUserToken::Main Delete call", true);

  $user = getHttpVal('user', '');
  
  if (delUserMap($id)) {
	$_SESSION['alert'] = 'User-'.$user.' mapped token deleted successfully';
  } else {
	$_SESSION['alert'] = 'Failed to delete User-'.$user.'! mapped token '.$contactAdm;
  } 
	
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

} elseif (strcmp($act,'Add')==0) {

  writeLog("ListUserToken::Main Add called", true);
  ///	lName	uToken	uStatus	uGroup	uEndDate
  $usreToken = getHttpVal('uToken', 1); /// modhex encoded
  $loginName = getHttpVal('lName', '');
  $userStatus = getHttpVal('uStatus', 1);
  $validity = getHttpVal('uValidity', '');
  $userEndDate = getHttpVal('uEndDate', '');
  $userStartDate = getHttpVal('uStartDate', '');
  $dt2=date("Y-m-d H:i:s");
  $devId = substr($usreToken, 0, 12);
  $tokenID = modhexToB64($devId);
  
  if(!isTokenAssign($tokenID)) {
    $stmt = 'CALL InsertUserMapKey('.mysql_quote($loginName).', '.mysql_quote($tokenID).
      ', '.mysql_quote($validity).', '.mysql_quote($userStartDate).', '.mysql_quote($userEndDate).', '.$userStatus.')';
  
    writeLog("ListUserToken::Main Add Qry :: ".$stmt, true);
  
    if ($r = query($stmt)) {
      $_SESSION['alert'] = 'User-'.$loginName.' with TokenID-'.$usreToken.' is mapped successfully';
    } else {
      $_SESSION['alert'] = 'User mapping failed! '.$contactAdm;
    }	
  } else {
  	$_SESSION['alert'] = 'TokenID-'.$usreToken.' is already mapped.';
  }
  
  
  writeLog("ListUserToken::Main Add Status :: ".$r, true);  
	
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

} else {
  writeLog("ListUserToken::Main selecting call call", true);  
  if (strcmp($act,'Retrieve')==0) {
  	
    writeLog("ListUserToken::Main Retrieve call", true);
    $id_type = getHttpVal('idtype', '');
    $searchtxt = getHttpVal('searchtxt', 1);
    
    $act = 'findkey';
    $attrName=getHttpVal('attr_name', $id_type);
    $attrVal=getHttpVal('attr_val', $searchtxt);    
    
    //idtype, searchtxt
  }
}

if (showUserMapping($act, $start, $attrName, $attrVal) == 0) {
    echo '<h4>No Mappings!</h4>';
}

// If client id = 0, meaning it's the root user, display all clients
function displayMapping($row, $toggle) {
  
  $client = $_SESSION['client'];
  $mapid = $row['map_id'];

  echo '<tr'.($toggle ? ' bgcolor=#eeeeee>' : '>');
  echo '<form method=POST action=list_user_token.php>'.
    '<input name=act type=hidden value=upd_key>'.
    '<input name=clientId type=hidden value='.$client.'>'.
    '<input name=id type=hidden value='.$mapid.'>'.
    '<input name=user type=hidden value='.$row['login_name'].'>'.
    '<td align=center valign=center><font size=2>';
  
  /*
  if ($keyId == $_SESSION['keyid']) {
  	echo '<img src=images/yubiright_16x16.gif title="This is the admin Yubikey you are using to log in!"><p>';
  } else if (isAdmKey($keyId)) {
  	echo '<img src=images/admkey.gif title="This is an admin Yubikey"><p>';
  }*/
  
  echo  $row['login_name'].'</td>'; /// User Name
  ///  Token ID
  $tokId = $row['tokenId'];
  writeLog("ListUserToken::displayMapping TokenID = ".$row['tokenId'] , true);
  echo '<td align=center valign=center><font size=2>' . $tokId .
		'<br>('. b64ToModhex($tokId) .')<br>('. b64ToHex($tokId).')</td>';
  //echo  '<td align=center valign=center><font size=2>'.$tokId.'</td>'; /// TokenID

  ///  Map Status
  echo '<td align=center valign=center><font size=2>';
  echo '<select name=status>';
  echo '<option value="0" '.($row['map_status']==0 ? 'selected' : '').'>Inactive'.
  	 '<option value="1" '.($row['map_status']==1 ? 'selected' : '').'>Active';
  echo '</select>';
  echo '</td>';

    ///  Validity Type
  echo '<td align=center valign=center><font size=2>';
  echo '<select name=type>';
  echo '<option value="infinity" '.($row['validity_type']==infinity ? 'selected' : '').'>Infinity'.
  	 '<option value="demo" '.($row['validity_type']==demo ? 'selected' : '').'>Demo';
  echo '</select>';
  echo '</td>';

  
  /*
  echo '<td><font size=1>' . $row['created'] . '</td>';
  echo '<td><font size=1>' . $row['accessed'] . '</td>';
  
  echo '<td><input name=counter value="'.$row['counter'].'" size=2 maxlength=9></td>';
  if (isRootAdm()) {
  	echo '<td><font size=1>' . $row['low'] . '</td>'.
  		 '<td><font size=1>' . $row['high'] . '</td>';
  }
  */
  
  echo '<td align=center valign=center><textarea name=startdate cols=15 rows=1 class=inputtxt>'.$row['start_date'].'</textarea></td>';
  echo '<td align=center valign=center><textarea name=enddate cols=15 rows=1 class=inputtxt>'.$row['end_date'].'</textarea></td>';
  echo '<td align=center valign=center><input name=act type=submit value=Update class=buttonLinkSmall>&nbsp;'.
  	 '<input name=act type=submit value=Delete class=buttonLinkSmall></form></td></tr>';
  	
} // End displayMapping

// $act: operation code = findkey | list_keys
// $otp: modhex OTP from a Yubikey
function showUserMapping($act, $start, $attrName, $attrVal) {
  $client = $_SESSION['client'];
  //echo 'act='.$act.', attrName='.$attrName.', val='.$attrVal;
  $stmt = 'select m.map_id, ur.login_name, t.tokenId, m.validity_type, m.start_date, m.end_date, m.map_status'.
		' FROM userkeymap m, users ur, yubikeys t WHERE (m.user_id = ur.user_id and m.key_id = t.id) ';

  //select m.map_id, ur.user_name, t.tokenId, m.validity_type, m.end_date, m.map_status from userkeymap m, users ur, yubikeys t where (m.user_id = ur.user_id and m.key_id = t.id) and ur.client_id = 1678
  
  if ($act == 'findkey') {
	if (isRootAdm() && $attrName=='client_id' && is_numeric($attrVal)) { // adm can see keys of any client
  		$stmt .= 'AND client_id='.$attrVal; /// need to think about it
  	} else if ($attrName=='loginName') {
  		$stmt .= 'AND ur.login_name='.mysql_quote($attrVal);
	} else if ($attrName=='otp') {
		$devId = substr($attrVal, 0, 12);
  		$stmt .= 'AND t.tokenId='.mysql_quote(modhexToB64($devId));
	} else {
  		$act = 'list_keys';
  	}
  } else {
  	$act = 'list_keys';
  }

  if (!isRootAdm()) { // If not root, can only see your own Yubikeys
   	if (strpos($stmt, 'WHERE') === false) { 
  		$stmt .= ' WHERE '; 
  	} else {
  		$stmt .= ' AND ';
  	}
  	$stmt .= ' ur.client_id='.$client;
  }
  
  $stmt .= ' LIMIT ' . $start . ', ' . MAX_PER_PAGE;
  
  writeLog($stmt, true);
  
  echo '<table border=0 width=100%><tr><td valign=top colspan=9 align=left><font size=2>';
  
  if (isRootAdm()) {
    if ($attrName == 'client_id') {
    	echo makePopupURL('edit_client.php?client='.$attrVal,'Client-'.$attrVal,500,'#BB0000','Client Info').
		  ' has '.numOfYubikeys($attrVal,1).' active Yubikeys, '.
    	  numOfYubikeys($attrVal,0).' inactive Yubikeys.';
    } else {
		echo 'There are '.numOfUsers(-1,1).' active Users, '.numOfYubikeys(-1,1).
			' active Yubikeys.';
    }
  } else {
    $a = getClientUserKeyInfo($client);
  	echo 'You have '.$a['num_active_user'].' active Users, '.$a['num_active_key'].' active Yubikeys.';
  }
  funcBar($act, $attrName, $attrVal);
  echo '</td></tr><tr><td height=8></td></tr>';
   
  ////// Find matching yubikeys
  //   
  //if (strlen($attrVal) < 1) { return 1; }
  $r = query($stmt);
  $n=mysql_num_rows($r);
  writeLog("ListUserToken::showUserMapping Row Count = ".$n , true);  	
  
  /// Col. Headers
  $title = '<tr bgcolor=#ADFF2F><th><font size=1>User Name</th>';
  if (isRootAdm()) {
	//$title .= '<th><font size=1>Client</th>';
  }
  $title .= '<th><font size=1>YubikeyID<br>base64<br>(modhex)<br>(hex)</th><th><font size=1>Status</th><th><font size=1>Validity Type</th><th><font size=1>Start Date</th><th><font size=1>End Date</th>';
  if (isRootAdm()) {
  //	$title .= '<th><font size=1>Low</th><th><font size=1>High</th>';
  }
  
  $title .= '<th></th></tr>'; // not need (req. Testing)
  
  echo $title;
  /// Col. Headers End
  
  $i=0;
  while ($row=mysql_fetch_assoc($r)) {  
	displayMapping($row, $i % 2);
//	print_r($row);
	if (++$i % 21 == 0) {
		echo $title;
	}
  }
  
  mysql_free_result($r);
  echo '</table>';
  
  echo '<br><font color=#008080 size=2><b>Showing ' . $i . ' record(s)</b></font><br><br>';
  
  if ($i < MAX_PER_PAGE) {
  	return ($i > 0 ? $i : -1);
  }
  
  echo '<h3><a href=#top>^ TOP</a><center><a name=BOT></a>';
  
  if ($attrName =='client_id') {
  	$filter = '&act=findkey&attr_name=client_id&attr_val='.$attrVal;
  } else {
  	$filter ='';
  }
  
  if ($start > 0) {
  	if (($s = $start - MAX_PER_PAGE) < 0) { $s = 0; }  	
  	echo '<a href=list_user_token.php?act=list_keys&start='.$s.$filter.'>PREV</a> | ';
  }

  if ($i >= MAX_PER_PAGE-1) {  	
  	echo '<a href=list_user_token.php?act=list_keys&start='.($start+MAX_PER_PAGE).$filter.'>NEXT</a>';
  }
  
  echo '</h3></center>';
    
  return $n;

} // End showMyAccts

// op = list_keys, findkey
function funcBar($act, $attrName) {
	global $page;

    echo '<hr size=1><table><tr><td valign=top><img src=images/arrow.jpg></td>'.
      '<td nowrap valign=bottom><a href=#DOWN onclick="javascript:showAddUserToken(0,'.$_SESSION['client'].');">'.
      '<b><font color=#008080 size=2><b> Add a yubikey mapped >></b></font></a>'.
      '<p><div id=mapkey></div></td></tr></table>';
      	
	echo '<table border=0 width=80%>'.
	  '<tr><td colspan=9 height=10></td></tr>';

    echo '<tr>';

	if ('list_keys' != $act) {
    	echo '<tr><td valign=top> ';
    	divBut(150, $page.'?act=list_keys','<font size=2>>> List of Mapped Users</font>');
    	echo '</td><td width=10></td><td width=30 nowrap valign=top>&nbsp;or&nbsp;</td>';
	}

    echo '<tr><td colspan=9 align=left><hr size=1>'.     
      '<form autocomplete=off method=POST action=list_user_token.php>'.
	  '<table border=0 width=90%>'.
	  '<tr><td colspan=9 align=center><font color=#008080 size=2><b>'.
	   'List of the user and token ID association for the Client:</b><br><br>'.
	  '</td></tr>'.
	  '<tr><td valign=top>' .
	  '<font size=2 color=#AA0000><p>'.
	  	'» Choose a Search type (login name or OTP ):<br>'.
		'<select id=idtype name=idtype>'.
	    '<option value=loginName>Login Name'.
		'<option value=otp>OTP or TokenID'.
	    '</select></td>'.
	    '<td align=left>»</td>'.
		'<td><font size=2 color=#AA0000>Enter the search text:</font><br>'.
		'<textarea name=searchtxt id=searchtxt rows=1 cols=37"></textarea><p>'.
	  '</td><td>»</td><td>' .
	  '<input name=act type=submit value=Retrieve class=buttonLinkSmall>'.	  
	  '</td></tr></table>'.
	  '</form>'.
	  
      '</td></tr>';  	
  	
	echo '</table><hr size=1>';
}

?>

<script>
hideLoading();
</script>
</body>
</html>
